package com.example.gcode;

//import java.io.File;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.enums.TargetApi;
import com.externalapi.CloudServiceHandler;
import com.gcloud.googledrive.ListGoogleFile;
import com.gcloud.googledrive.UploadGoogleFile;
import com.gfilechooser.utils.FileUtils;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.result.ApiResult;
import com.utils.Constants;

import android.accounts.AccountManager;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
//import android.net.Uri;<>
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.sax.StartElementListener;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.google.api.services.drive.Drive.Files;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;

public class FileOptionsActivity extends Activity {
	static final int REQUEST_ACCOUNT_PICKER = 1;
	static final int REQUEST_AUTHORIZATION = 2;
	static final int CAPTURE_IMAGE = 3;
	private static Uri fileUri;
	private static Drive service;
	private GoogleAccountCredential credential;

	private final int REQUEST_CODE = 1;
	private final int REQUEST_ACCOUNT = 2;
	private final String TAG = FileOptionsActivity.class.getSimpleName();
	private TargetApi target;
	private GoogleAccountCredential googleCredential;
	Bundle intentExtras;
	String action;
	ApiResult result = new ApiResult();
	CloudServiceHandler cloudService = new CloudServiceHandler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fileoptionslayout);

		ListView listView = (ListView) findViewById(R.id.listViewFileOptions);
		BaseAdapter baseAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, getFileOptions());
		listView.setAdapter(baseAdapter);
		registerForContextMenu(listView);
		intentExtras = getIntent().getExtras();
		if (intentExtras.containsKey(Constants.target)) {
			Log.i(TAG, "target found ");
			target = (TargetApi) intentExtras.get(Constants.target);
			Log.i(TAG, "target founded: " + target.name());
		} else {
			Log.i(TAG, "target not founded ;) ");
		}

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String item = ((TextView) view).getText().toString();
				Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG)
						.show();
				Log.i(TAG, "target founded on item click: " + target.name());
				if (item.equals(Constants.upload)) {
					credential = GoogleAccountCredential.usingOAuth2(
							FileOptionsActivity.this, DriveScopes.DRIVE);
					startActivityForResult(credential.newChooseAccountIntent(),
							REQUEST_ACCOUNT_PICKER);
					// methodToCall();
					// showChooser();
				}
			}

		});
	}

	private String[] getFileOptions() {
		String fileOptions[] = { Constants.share, Constants.upload,
				Constants.delete, Constants.download, Constants.move,
				Constants.createDirectory };
		return fileOptions;
	}

	private void showChooser() {
		Intent target = FileUtils.createGetContentIntent();
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooserTitle));
		// intent.putExtra(Constants.target,
		// (TargetApi) intentExtras.get(Constants.target));
		// intent.putExtra("sipi", "si trae algo vos");
		try {
			startActivityForResult(intent, CAPTURE_IMAGE);
		} catch (ActivityNotFoundException e) {
			Log.i(TAG, "Show Chooser fail, not exeption");
		}
	}

	public void methodToCall() {
		String accountName = "guilletec@gmail.com";
		Log.i("methodToCall: ", accountName);
		// String methodName = "recurringProcessor";
		// Log.i(methodName, accountName);
		// if (accountName != null) {
		// credential.setSelectedAccountName(accountName);
		// service = getDriveService(credential);
		// // startCameraIntent();
		// // retrieveAllFiles();

		try {
			Log.i("tag", "before to retrieve all files");
			retrieveAllFiles();
			Log.i("tag", "something goes perfect from picker");
		} catch (UserRecoverableAuthIOException e) {
			startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
		} catch (IOException e) {
			Log.i("tag", "something goes wrong getting files in picker: " + e);
		} catch (Exception e) {

		}
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		switch (requestCode) {
		case REQUEST_ACCOUNT_PICKER:
			if (resultCode == RESULT_OK && data != null
					&& data.getExtras() != null) {

				  String accountName = data
				  .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
//				String accountName = "guilletec@gmail.com";
				if (accountName != null) {
//d					credential.setSelectedAccountName(accountName);
//					service = getDriveService(credential);
					Log.i("onActivityResult picker: ", accountName);
					// String methodName = "recurringProcessor";
					// Log.i(methodName, accountName);
					// if (accountName != null) {
					credential.setSelectedAccountName(accountName);
					service = getDriveService(credential);					
//					 startCameraIntent();					
					Log.i(TAG, "before to list");
					ListGoogleFile listGoogle = new ListGoogleFile(service,
							FileOptionsActivity.this);
					Log.i(TAG, "before to execute");
					listGoogle.execute();
					Log.i(TAG, "after execute");

//					 methodToCall();

				}
				// // retrieveAllFiles();
				// try {
				// Log.i("tag", "before to retrieve all files");
				// retrieveAllFiles();
				// Log.i("tag", "something goes perfect from picker");
				// } catch (IOException e) {
				// Log.i("tag",
				// "something goes wrong getting files in picker: "
				// + e);
				// }
				// }
			}
			break;
		case REQUEST_AUTHORIZATION:
			if (resultCode == Activity.RESULT_OK) {
				saveFileToDrive();
				// try {
				// retrieveAllFiles();
				// Log.i("tag", "something goes perfect");
				// } catch (IOException e) {
				// Log.i("tag", "something goes wrong getting files: " + e);
				// }
			} else {
				startActivityForResult(credential.newChooseAccountIntent(),
						REQUEST_ACCOUNT_PICKER);
			}
			break;
		case CAPTURE_IMAGE:
			if (resultCode == Activity.RESULT_OK) {
				saveFileToDrive();
				// try {
				// retrieveAllFiles();
				// Log.i("tag", "something goes perfect capture image");
				// } catch (IOException e) {
				// Log.i("tag", "something goes wrong capture image: " + e);
				// }
			}
		}
		// switch (requestCode) {
		// case REQUEST_ACCOUNT:
		// if (resultCode == RESULT_OK && data != null
		// && data.getExtras() != null) {
		// String accountName = data
		// .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
		// if (accountName != null) {
		// googleCredential.setSelectedAccountName(accountName);
		// GoogleDriveApi.service = getDriveService(googleCredential);
		// showChooser();
		// }
		// }
		// break;
		// case REQUEST_CODE:
		// if (resultCode == Activity.RESULT_OK) {
		// cloudService.setContext(this);
		// result = cloudService.insertFile(target, data);
		// if (!result.isSuccess()) {
		// Log.i(TAG, "request code fail");
		// } else {
		// Log.i(TAG, "request code success");
		// }
		// } else {
		// startActivityForResult(
		// googleCredential.newChooseAccountIntent(),
		// REQUEST_ACCOUNT);
		// }
		// break;
		// // case CAPTURE_IMAGE:
		// // if (resultCode == Activity.RESULT_OK) {
		// // showChooser();
		// // }
		// }
	}

	// @Override
	// protected void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// switch (requestCode) {
	// case REQUEST_CODE:
	// Log.i(TAG, "requesting code");
	// // If the file selection was successful
	// if (resultCode == RESULT_OK) {
	// if (data != null) {
	// // Get the URI of the selected file
	// // final Uri uri = data.getData();
	// try {
	// // Create a file instance from the URI
	// // final File file = FileUtils.getFile(uri);
	// // Toast.makeText(FileOptionsActivity.this,
	// // "File Selected: " + file.getAbsolutePath(),
	// // Toast.LENGTH_LONG).show();
	// //beforeExecuteAction();
	// cloudService.setContext(this);
	// result = cloudService.insertFile(target, data);
	// if (!result.isSuccess()
	// && result.getErrorCode() == Constants.REQUEST_GOOGLE_CREDENTIAL_ERROR) {
	// startActivityForResult(getIntent(), REQUEST_ACCOUNT);
	// } else if (result.isSuccess()) {
	// Toast.makeText(this, "File upload success",
	// Toast.LENGTH_LONG).show();
	// }
	// } catch (Exception e) {
	// Log.e("FileSelectorTestActivity", "File select error",
	// e);
	// Toast.makeText(this, "File error uploading unsuccess",
	// Toast.LENGTH_LONG).show();
	// }
	// }
	// }
	// break;
	// case REQUEST_ACCOUNT:
	// Log.i(TAG, "requesting account");
	// if (resultCode == RESULT_OK && data != null
	// && data.getExtras() != null) {
	// Log.i(TAG, "result ok, data not null");
	// String accountName = data
	// .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
	// if (accountName != null) {
	// Log.i(TAG, accountName);
	// googleCredential.setSelectedAccountName(accountName);
	// GoogleDriveApi.service = getDriveService(googleCredential);
	// startActivityForResult(data, REQUEST_CODE);
	// }
	// }
	// break;
	// }
	// super.onActivityResult(requestCode, resultCode, data);
	// }

	// private void beforeExecuteAction() {
	// String methodName = "beforeExecuteAction()";
	// Log.i(TAG, methodName);
	// if (target.equals(TargetApi.GOOGLEDRIVE)) {
	// initGoogleCredentialSubActivity();
	// }
	// }
	//
	// private void initGoogleCredentialSubActivity() {
	// String methodName = "initGoogleCredentialSubActivity()";
	// Log.i(TAG, methodName);
	// googleCredential = GoogleAccountCredential.usingOAuth2(this,
	// DriveScopes.DRIVE);
	// startActivityForResult(googleCredential.newChooseAccountIntent(),
	// REQUEST_ACCOUNT);
	// }

	private Drive getDriveService(GoogleAccountCredential credential) {
		return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
				new GsonFactory(), credential).build();
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	private void saveFileToDrive() {
//		UploadGoogleFile uploadF=new UploadGoogleFile(service, fileUri, FileOptionsActivity.this);
//		uploadF.execute();
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// File's binary content
					java.io.File fileContent = new java.io.File(fileUri
							.getPath());
					FileContent mediaContent = new FileContent("image/jpeg",
							fileContent);

					// File's metadata.
					File body = new File();
					body.setTitle(fileContent.getName());
					body.setMimeType("image/jpeg");

					File file = service.files().insert(body, mediaContent)
							.execute();
					if (file != null) {
						showToast("Photo uploaded: " + file.getTitle());
						startCameraIntent();
					}
				} catch (UserRecoverableAuthIOException e) {
					startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		t.start();
	}

	private void startCameraIntent() {
		String mediaStorageDir = Environment.getExternalStoragePublicDirectory(
				Environment.DIRECTORY_PICTURES).getPath();
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
				.format(new Date());
		fileUri = Uri.fromFile(new java.io.File(mediaStorageDir
				+ java.io.File.separator + "IMG_" + timeStamp + ".jpg"));

		Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
		startActivityForResult(cameraIntent, CAPTURE_IMAGE);
	}

	private static List<File> retrieveAllFiles() throws Exception {

		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				List<File> result = new ArrayList<File>();
				Files.List request = null;
				try {
					request = service.files().list();
					Log.i("retrieveAllFiles()", "getting files");
				} catch (IOException e1) {
					Log.i("retrieveAllFiles()", "something goes really wrong");
				}
				Log.i("retrieveAllFiles()", "to execute get Files");
				if (request == null) {
					Log.i("retrieveAllFiles() inside run",
							"to execute get Files inside run");
					return;
				}
				Log.i("retrieveAllFiles()", "request well formed ");
				do {
					try {
						FileList files = request.execute();
						result.addAll(files.getItems());
						request.setPageToken(files.getNextPageToken());
					} catch (IOException e) {
						System.out.println("An error occurred: " + e);
						request.setPageToken(null);

					}
				} while (request.getPageToken() != null
						&& request.getPageToken().length() > 0);
				for (File file : result) {
					Log.i("RetrieveAllFiles", "File title: " + file.getTitle());
				}
			}

		});
		t.start();

		return null;
	}

	static String fileId;

	private static void printFile() {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					File file = service.files().get(fileId).execute();

					System.out.println("Title: " + file.getTitle());
					System.out.println("Description: " + file.getDescription());
					System.out.println("MIME type: " + file.getMimeType());
				} catch (IOException e) {
					System.out.println("An error occured: " + e);
				}
			}

		});
		t.start();
	}

	private static File file;

	private static InputStream downloadFile() {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {

				if (file.getDownloadUrl() != null
						&& file.getDownloadUrl().length() > 0) {
					try {
						HttpResponse resp = service
								.getRequestFactory()
								.buildGetRequest(
										new GenericUrl(file.getDownloadUrl()))
								.execute();
						return;
					} catch (IOException e) {
						// An error occurred.
						e.printStackTrace();
						return;
					}
				} else {
					// The file doesn't have any content stored on Drive.
					return;
				}
			}

		});
		t.start();
		return null;
	}

}
